package com.hnit.service;


import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import dev.langchain4j.community.model.dashscope.QwenEmbeddingModel;
import dev.langchain4j.community.store.embedding.clickhouse.ClickHouseEmbeddingStore;
import dev.langchain4j.data.embedding.Embedding;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.store.embedding.EmbeddingSearchRequest;
import dev.langchain4j.store.embedding.EmbeddingSearchResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ToolServices {
    @Autowired
    private ClickHouseEmbeddingStore scoreEmbeddingStore;
    @Autowired
    private QwenEmbeddingModel embeddingModel;


    // 添加 setter 方法
    public void setScoreEmbeddingStore(ClickHouseEmbeddingStore scoreEmbeddingStore) {
        this.scoreEmbeddingStore = scoreEmbeddingStore;
    }
    @Tool("学生查分工具。用户提供学号、姓名或班级信息，返回该学生的成绩与解释")
    public String queryScoreByVector(@P("用户输入") String userQuery) {

        try {

            // 1. 生成查询向量
            Embedding embedding = embeddingModel.embed(userQuery).content();
            // 2. 向量检索（匹配前1条）
            EmbeddingSearchResult<TextSegment> result = scoreEmbeddingStore.search(EmbeddingSearchRequest.builder()
                    .queryEmbedding(Embedding.from(embedding.vector()))
                    .maxResults(1)
                    .minScore(0.7)
                    .build());
            // 3. 返回匹配内容
            List<TextSegment> matches = result.matches().stream()
                    .map(match -> match.embedded())
                    .collect(Collectors.toList());
            if (matches.isEmpty()) {
                return "未找到与该学生相关的成绩信息，请确认学号或姓名。";
            }
            System.out.println("matches = " + matches);
            return matches.get(0).text();  // 返回原始文本结果（如：成绩 + 解释）
        } catch (Exception e) {
            e.printStackTrace();
            return "查询成绩失败：" + e.getMessage();
        }
    }
}
